package db

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"kubeInstall/conf"
	"kubeInstall/pkg/logger"
	"kubeInstall/server/models/cluster"
	"kubeInstall/server/models/file"
	"kubeInstall/server/models/storageplugin"
	"kubeInstall/server/models/user"
	"strings"
	"time"
)

type Config struct {
	DBType                string
	Host                  string `json:"host,omitempty"`
	Username              string `json:"username,omitempty"`
	Password              string `json:"password,omitempty"`
	DBName                string `json:"db_name"`
	MaxIdleConnections    int    `json:"maxIdleConnections,omitempty"`
	MaxOpenConnections    int    `json:"maxOpenConnections,omitempty"`
	MaxConnectionLifeTime time.Duration
	Debug                 bool
}

func AutoMigrate(db *gorm.DB) {

	if dbType := conf.DatabaseSetting.Type; strings.ToLower(dbType) == "mysql" {
		db = db.Set("gorm:table_options", "ENGINE=InnoDB")
	}

	db.AutoMigrate(
		new(file.SysPackage),
		new(cluster.Host),
		new(cluster.Credential),
		new(user.User),
		/*	new(cluster.SysPackage),
			new(cluster.DockerImage),*/
		new(cluster.Cluster),
		new(storageplugin.StorageNFS))
}

var Db *gorm.DB

func init() {
	// init db
	var err error
	Db, err = gorm.Open(conf.DatabaseSetting.Type, fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local",
		conf.DatabaseSetting.User,
		conf.DatabaseSetting.Password,
		conf.DatabaseSetting.Host,
		conf.DatabaseSetting.Name))

	if err != nil {
		logger.Fatal("models.Setup err: %v", err)
	}

	err = Db.DB().Ping()
	if err != nil {
		logger.Fatal("connect db error: %s", err.Error())
		Db.Close()
	}
	if conf.DatabaseSetting.EnableDebug {
		Db.LogMode(true)
	}

	Db.SingularTable(true)
	if conf.DatabaseSetting.EnableAutoMigrate {
		AutoMigrate(Db)
	}
	logger.Info("init db successfully ")
}
